import { H3Event, eventHandler, readBody } from "h3";
import { generateQuiz, generateQuizFromMistakes } from "../aiService.js";

export const generateQuizHandler = eventHandler(async (event) => {
    try {
        const body = (await readBody(event));
        const { topic, questions } = body;

        let quiz;
        if (questions && Array.isArray(questions)) {
            quiz = await generateQuizFromMistakes(questions);
        } else if (topic && typeof topic === "string") {
            quiz = await generateQuiz(topic);
        } else {
            return {
                error: "Topic (string) or questions (array) is required",
                status: 400,
            };
        }

        return {
            success: true,
            data: quiz,
        };
    } catch (error) {
        console.error("Quiz generation error:", error);
        return {
            error: error.message || "Failed to generate quiz",
            status: 500,
        };
    }
});
